/*
 * Copyright (C) 2010 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.common.widget;

import java.io.File;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mol.market.R;
import com.mol.market.Session;
import com.mol.market.common.util.ImageUtils;
import com.mol.market.common.util.Utils;

/**
 * Splash 图展示控件，点击动画展开全图
 * 
 * @author andrew.wang
 * @date   2011-12-15
 * @since  Version 0.9
 *
 */
public class SplashView extends RelativeLayout implements OnClickListener {

    /** 默认的高度(200dp) */
    private static final int HEIGHT = 210;
    
    private static final int DURATION = 1000;
    
    /** 背景图隐藏高度 */
    private static final int HIDE_HEIGHT = 90;
    
    /** 标题的高度(32dp)*/
    private final int TITLE_HEIGHT = 32;
    
    /** 屏幕像素拉伸系数 */
    private float mDensity;
    
    /** 屏幕高度 */
    private int mHeight;
    
    private int mTitleHeight;
    
    private boolean isShow;
    
    private boolean isInit;
    
    /** 小展示图的高度 */
    private int mSmallViewHeigh;
    
    private ImageView mBackground;
    private TextView mTitle;
    
    private int FOOTER_VIEW_ID = 10;
    
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mHeight = MeasureSpec.getSize(heightMeasureSpec);
        ensureLayoutParams();
        if (!isInit) {
            init();
            addView(mFooterView);
            isInit = true;
        }
    }
    
    public SplashView(Context context, View footer) {
        super(context);
        DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
        
        mDensity = metrics.density;
        
        mSmallViewHeigh = (int) (HEIGHT * mDensity);
        mTitleHeight = (int) (TITLE_HEIGHT * mDensity);
        
        LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        // TODO: hard code
//        lp.topMargin = mSmallViewHeigh;
        mFooterView = footer;
        mFooterView.setId(FOOTER_VIEW_ID);
        mFooterView.setLayoutParams(lp);
    }
    
    public void init() {
        mTitle = createTitleView();
        mBackground = createBackgroundView();
        ImageView shadow = new ImageView(getContext());
        LayoutParams rl = new LayoutParams(LayoutParams.FILL_PARENT, (int) (4 * mDensity));
        rl.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        shadow.setLayoutParams(rl);
        shadow.setBackgroundResource(R.drawable.top_shadow);
        addView(mBackground);
        addView(mTitle);
        addView(shadow);
    }
    

    private ImageView createBackgroundView() {
        
        ImageView v = new ImageView(getContext());
        LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        lp.topMargin = -HIDE_HEIGHT;
        v.setLayoutParams(lp);
        v.setScaleType(ScaleType.MATRIX);
        v.setClickable(true);
        v.setOnClickListener(this);
        
        File splashFile = new File(getContext().getFilesDir(), "splash.png");
        Bitmap bmp = null;
        if (splashFile.exists()) {
            try {
                BitmapFactory.Options o = new BitmapFactory.Options();
                o.inPurgeable = true;
                o.inInputShareable = true;
                bmp = BitmapFactory.decodeFile(splashFile.getAbsolutePath(), o);
            } catch (OutOfMemoryError e) {
                Utils.E("initSplashBg OutOfMemoryError", e);
            }
        } else {
            bmp = BitmapFactory.decodeResource(getResources(), R.drawable.splash);
        }
        Bitmap scaledBitmap = ImageUtils.scaleBitmap(getContext(), bmp);
        v.setImageBitmap(scaledBitmap);
        return v;
    }
    
    /*
     * 创建标题View
     */

    private TextView createTitleView() {
        
        TextView v = new TextView(getContext());
        LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, mTitleHeight);
        // TODO: hard code
//        lp.topMargin = mSmallViewHeigh - mTitleHeight;
        lp.addRule(RelativeLayout.ABOVE, FOOTER_VIEW_ID);
        v.setLayoutParams(lp);
        v.setText(Session.get(getContext()).getVersionName());
        v.setGravity(Gravity.CENTER_VERTICAL|Gravity.LEFT);
        v.setBackgroundResource(R.drawable.scroll_image_title_bg);
        return v;
    }
    
    private boolean mIsAnimationEnd = true;
    private Animation mBackgroundShowAnimation;
    private Animation mBackgroundHideAnimation;
    private Animation mTitleShowAnimation;
    private Animation mTitleHideAnimation;
    private Animation mFooterShowAnimation;
    private Animation mFooterHideAnimation;
    

    private AnimationListener mAnimationListener = new AnimationListener() {
        
        @Override
        public void onAnimationStart(Animation animation) {
            mIsAnimationEnd = false;
        }
        
        @Override
        public void onAnimationRepeat(Animation animation) {
        }
        
        @Override
        public void onAnimationEnd(Animation animation) {
            if(animation.equals(mFooterHideAnimation)) {
                setEnable(mFooterView,true);
            }
            mIsAnimationEnd = true;
        }
    };
    
    /*
     * 计算两种状态的展示像素参数
     */
    private void ensureLayoutParams() {
        
        mBackgroundShowAnimation = new TranslateAnimation(0, 0, 0, HIDE_HEIGHT);
        mBackgroundShowAnimation.setDuration(DURATION);
        mBackgroundShowAnimation.setFillAfter(true);
        
        mBackgroundHideAnimation= new TranslateAnimation(0, 0, HIDE_HEIGHT, 0);
        mBackgroundHideAnimation.setDuration(DURATION);
        mBackgroundHideAnimation.setFillAfter(true);
        
        int titleStep = mFooterView.getHeight();
        if (titleStep == 0) {
            titleStep = mHeight - mFooterView.getTop();
        }
        mTitleShowAnimation = new TranslateAnimation(0, 0, 0, titleStep);
        mTitleShowAnimation.setDuration(DURATION);
        mTitleShowAnimation.setFillAfter(true);
        
        mTitleHideAnimation = new TranslateAnimation(0, 0, titleStep, 0);
        mTitleHideAnimation.setDuration(DURATION);
        mTitleHideAnimation.setFillAfter(true);
        
        mFooterShowAnimation = new TranslateAnimation(0, 0, 0, titleStep);
        mFooterShowAnimation.setDuration(DURATION);
        mFooterShowAnimation.setFillAfter(true);
        mFooterShowAnimation.setAnimationListener(mAnimationListener);
        
        mFooterHideAnimation = new TranslateAnimation(0, 0, titleStep, 0);
        mFooterHideAnimation.setDuration(DURATION);
        mFooterHideAnimation.setFillAfter(true);
        mFooterHideAnimation.setAnimationListener(mAnimationListener);
    }

    private View mFooterView;

    public void setFooterView(View v) {
        LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        // TODO: hard code
        lp.topMargin = mSmallViewHeigh;
        v.setLayoutParams(lp);
        v.setBackgroundColor(Color.BLUE);
        mFooterView = v;
    }
    

    @Override
    public void onClick(View v) {
        if (!mIsAnimationEnd) {
            // 避免多次点击
            return;
        }
        setEnable(mFooterView,false);
        if (isShow) {
            mBackground.startAnimation(mBackgroundHideAnimation);
            mTitle.startAnimation(mTitleHideAnimation);
            mFooterView.startAnimation(mFooterHideAnimation);
        } else {
            mBackground.startAnimation(mBackgroundShowAnimation);
            mTitle.startAnimation(mTitleShowAnimation);
            mFooterView.startAnimation(mFooterShowAnimation);
        }
        isShow = !isShow;
    }
    
    private void setEnable(View view, boolean flag) {
        LinearLayout v = (LinearLayout) view;
        for (int i = 0; i < v.getChildCount(); i++) {
            v.getChildAt(i).setClickable(flag);
//            v.getChildAt(i).setOnClickListener(null);
        }
    }
    
}
